<?php

class html
{
	var $helpers = Array("Html");
    static protected $sys_id = 0;
    static protected $sys_func = 0;
    protected $icons = array(
    );

    function shadow_box($className, $content, $args = array())
    {

        $file_name['tl']    = $className.'-tl.png';
        $file_name['t']     = $className.'-t.png';
        $file_name['tr']    = $className.'-tr.png';
        $file_name['r']     = $className.'-r.png';
        $file_name['br']    = $className.'-br.png';
        $file_name['b']     = $className.'-b.png';
        $file_name['bl']    = $className.'-bl.png';
        $file_name['l']     = $className.'-l.png';

        $path = Application::rootUrlPath().Application::imgUrlPath();
        $out_before = "";

        $out_before .= '<div class="sys_box" style="'.$this->backgroundImageNotIE($path.$file_name['tl'], true).'">';
        $out_before .= '<div class="sys_ctr" style="'.$this->backgroundImageNotIE($path.$file_name['tr'], true).'">';
        $out_before .= '<div class="sys_cbl" style="'.$this->backgroundImageNotIE($path.$file_name['bl'], true).'">';
        $out_before .= '<div class="sys_cbr" style="'.$this->backgroundImageNotIE($path.$file_name['br'], true).'">';

        $out_before .= '<div class="sys_top" style="height: 8px; margin-left: 8px; margin-right: 8px; '.$this->backgroundImageNotIE($path.$file_name['t']).' //height: 0px; //margin-left: 0px; //margin-right: 0px;"></div>';

        $out_before .= '<div class="sys_left-container" style="'.$this->backgroundImageNotIE($path.$file_name['l']).'">';
        $out_before .= '<div class="sys_right-container" style="'.$this->backgroundImageNotIE($path.$file_name['r']).'">';
        $out_before .= '<div style="margin-left: 8px; margin-right: 8px; //margin-left: 0px; //margin-right: 0px;">';

        /*
        C O N T E N T
        */

        $out_after  = "";
        $out_after .= "</div>";
        $out_after .= "</div>";
        $out_after .= "</div>";

        $out_after .= '<div class="sys_bottom" style="height: 8px; margin-left: 8px; margin-right: 8px; '.$this->backgroundImageNotIE($path.$file_name['b']).' //height: 0px; //margin-left: 0px; //margin-right: 0px;"></div>';

        $out_after .= '</div>';
        $out_after .= '</div>';
        $out_after .= '</div>';
        $out_after .= '</div>';

        if (is_callable($content)) {
            echo $out_before;
            call_user_func_array($content, $args);
            echo $out_after;
        } else {
           return $out_before.$content.$out_after;
        }
    }

    function rounded_box($className, $content, $args = array())
    {
        $file_name['tl']    = $className.'-tl.png';
        $file_name['tr']    = $className.'-tr.png';
        $file_name['br']    = $className.'-br.png';
        $file_name['bl']    = $className.'-bl.png';

        $path = Application::rootUrlPath().Application::imgUrlPath();
        $out_before = "";

        $out_before .= '<div class="sys_box" style="'.$this->backgroundImageNotIE($path.$file_name['tl'], true).'">';
        $out_before .= '<div class="sys_ctr" style="'.$this->backgroundImageNotIE($path.$file_name['tr'], true).'">';
        $out_before .= '<div class="sys_cbl" style="'.$this->backgroundImageNotIE($path.$file_name['bl'], true).'">';
        $out_before .= '<div class="sys_cbr" style="'.$this->backgroundImageNotIE($path.$file_name['br'], true).'">';

        /*
        C O N T E N T
        */

        $out_after  = "";
        $out_after .= '</div>';
        $out_after .= '</div>';
        $out_after .= '</div>';
        $out_after .= '</div>';

        if (is_callable($content)) {
            echo $out_before;
            call_user_func_array($content, $args);
            echo $out_after;
        } else {
           return $out_before.$content.$out_after;
        }
    }

    protected function backgroundImage($url, $crop=false)
    {
        return "background-image:url({$url});";
    }

    protected function backgroundImageIE($url, $crop=false)
    {
        return "background-image:url({$url});-filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='{$url}',sizingMethod='crop');-background-image: none;";
    }

    protected function backgroundImageNotIE($url, $crop=false)
    {
        return "background-image:url({$url});-background-image: none;";
    }

	function image($path, $htmlAttributes = array())
	{
		$result = '';

		$url = $this->url($path);

		if (stripos($url, '.png')===strlen($url)-4) {
			$htmlAttributes = array_merge($this->imageInfo($url), $htmlAttributes);
			if (empty($htmlAttributes["style"])) {
			    $htmlAttributes["style"] = '';
			} elseif ($htmlAttributes["style"][strlen($htmlAttributes["style"])-1]!==';') {
			    $htmlAttributes["style"] .= ';';
			}
			$htmlAttributes["style"] .= "background-image:url('{$url}');filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='{$url}',sizingMethod='scale');//background-image: none;";
			$result = $this->_image('/style/pix.gif', $htmlAttributes);
		} else {
			$result = $this->_image($path, $htmlAttributes);
		}

		return $result;
	}

	protected function _image($path, $htmlAttributes = array())
	{
		$path = $this->url($path);

		if (!isset($htmlAttributes['alt'])) {
			$htmlAttributes['alt'] = '';
		}
		$htmlAttributes["src"] = $path;
		return "<img ".$this->_parseAttributes($htmlAttributes)." />";

	}

	function link($title, $url = null, $htmlAttributes = array(), $confirmMessage = false, $escapeTitle = true)
	{
		if ($url !== null) {
			$url = $this->url($url);
		} else {
			$url = $this->url($title);
			$title = $url;
			$escapeTitle = false;
		}
		$inactive = false;
		if (!empty($htmlAttributes['sys:inactive'])) {
			$inactive = true;
			unset($htmlAttributes['sys:inactive']);
		}

		if (isset($htmlAttributes['escape'])) {
			$escapeTitle = $htmlAttributes['escape'];
			unset($htmlAttributes['escape']);
		}
		if ($escapeTitle) {
			$title = str($title)->xmlEntities(ENT_NOQUOTES)->value;
		}

		if (! $inactive) {
    		if (!empty($htmlAttributes['confirm'])) {
    			$confirmMessage = $htmlAttributes['confirm'];
    			unset($htmlAttributes['confirm']);
    		}
    		if ($confirmMessage) {
    		    sys::uses("json");
    		    $confirmMessage = json::draw(str($confirmMessage)->value, "'");
    			$htmlAttributes['onclick'] = "return confirm({$confirmMessage});";
    		} elseif (isset($htmlAttributes['default']) && ! $htmlAttributes['default']) {
    			if (isset($htmlAttributes['onclick'])) {
    				$htmlAttributes['onclick'] .= ' event.returnValue = false; return false;';
    			} else {
    				$htmlAttributes['onclick'] = 'event.returnValue = false; return false;';
    			}
    			unset($htmlAttributes['default']);
    		}
    		$htmlAttributes["href"] = $url;
    		return "<a ".$this->_parseAttributes($htmlAttributes).">".$title."</a>";
		} else {
    		return "<span ".$this->_parseAttributes($htmlAttributes).">".$title."</span>";
		}
	}

	protected function imageInfo($path)
	{
		$result = array();

		$url = '';
		if (strpos($path, '://')) {
		    $url = parse_url($path);
		    $url = (isset($url['path']) ? $url['path'] : "").(isset($url['query']) ? "?{$url['query']}" : "").(isset($url['fragment']) ? "#{$url['fragment']}" : "");
		} else {
            $url = $path;
		}
		$url = str_replace('/', Application::ds(), $url);
		$full_path = Application::webRootPath().$url;

		static $cash = array();

		if (!isset($cash[$full_path])) {
		    if (file_exists($full_path) && is_readable($full_path) && ((bool)($img_source = @imagecreatefrompng($full_path))) && is_resource($img_source)) {
    			$cash[$full_path]["width"]  = imagesx($img_source);
    			$cash[$full_path]["height"] = imagesy($img_source);
		    } else {
    			$cash[$full_path]["width"]  = 0;
    			$cash[$full_path]["height"] = 0;
		    }
		}
		$result["width"]  = $cash[$full_path]["width"];
		$result["height"] = $cash[$full_path]["height"];

		return $result;
	}

	function iconLink($type, $title, $url = null, $htmlAttributes = array(), $confirmMessage = false, $escapeTitle = true)
	{
	    $args = func_get_args();
	    if (isset($args[3]["button"])) {
	        unset($args[3]["button"]);
	    }
	    return call_user_func_array(array($this, '_iconLink'), $args);
    }

	function iconButton($type, $htmlAttributes = array())
	{
	    $args = func_get_args();
	    $htmlAttributes = array();
	    if (isset($args[1])) {
            $htmlAttributes = $args[1];
	    }
	    $htmlAttributes["button"] = true;
	    if (!isset($args[0])) {
	        $args[0] = null;
	    }
	    $args[1] = null;
	    $args[2] = null;
	    $args[3] = $htmlAttributes;
	    return call_user_func_array(array($this, '_iconLink'), $args);
    }

	protected function _iconLink($type, $title, $url = null, $htmlAttributes = array(), $confirmMessage = false, $escapeTitle = true)
	{
	    if (!in_array($type, $this->icons)) {
	        return "";
	    }
	    $index = array_keys($this->icons, $type, true);
	    if (!isset($index[0])) {
	        return "";
	    }
	    $index = $index[0];

	    $alert = null;
	    $inactive = !empty($htmlAttributes["inactive"]);
	    $alert = !empty($htmlAttributes["inactive"]) && is_string($htmlAttributes["inactive"]) ? str($htmlAttributes["inactive"])->addslashes("'\"")->value : "";
	    if (array_key_exists("inactive", $htmlAttributes)) {
	        unset($htmlAttributes["inactive"]);
	    }
	    if (is_string($confirmMessage)) {
            $__confirmMessage = str($confirmMessage)->addslashes("'\"")->value;
	    } else {
	        $__confirmMessage = false;
	    }
        $confirmMessage = false;
        if (empty($htmlAttributes["onclick"])) {
            $htmlAttributes["onclick"] = '';
        }
	    if ($inactive) {
	        $pre_action = $alert ? "alert('".$alert."');" : "";
            $action = $pre_action.'return false;';
	        $htmlAttributes["onclick"] = $action.$htmlAttributes["onclick"];
        } elseif (is_string($__confirmMessage)) {
            $action = "if (!confirm('".$__confirmMessage."')) return false;";
	        $htmlAttributes["onclick"] = $action.$htmlAttributes["onclick"];
        }
	    if (isset($htmlAttributes["class"])) {
	        $htmlAttributes["class"] .= " ";
	    } else {
	        $htmlAttributes["class"] = "";
	    }
	    $htmlAttributes["class"] .= "icon".$index.($inactive ? "i" : "");

	    $notable = !empty($htmlAttributes["notable"]);
	    if (array_key_exists("notable", $htmlAttributes)) {
	        unset($htmlAttributes["notable"]);
	    }
	    $button = !empty($htmlAttributes["button"]);
	    if (array_key_exists("button", $htmlAttributes)) {
	        unset($htmlAttributes["button"]);
	    }
	    if ($title) {
	       $htmlAttributes["title"] = $title;
	    }

	    $html = "";
	    if ($button) {
	        unset($htmlAttributes["button"]);
    	    $htmlAttributes["class"] .= " icon-button sys_clear";
    	    $button_content = '<img src="'.$this->url(Application::imgUrlPath().'/pix.gif').'" class="sys_clear filler" />';
    	    $html = '<button'.$this->_parseAttributes($htmlAttributes).'>'.$button_content.'</button>';
        } else {
    	    $htmlAttributes["class"] .= " icon-link";
    	    $title = "";

    	    $html = $this->link($title, $url, $htmlAttributes, $confirmMessage, $escapeTitle);
    	    if (!$notable) {
        	    $html = '<td class="sys_clear">'.$html.'</td>';
    	    }
        }
	    return $html;
    }

    protected function _parseAttributes($options, $exclude = null)
    {
        if (! is_array($options)) {
            throw new ArgException();
        }
        if (! is_array($exclude)) {
            $exclude = array();
        }
        $default = array (
            'escape' => true
        );
        $options = array_merge($default, $options);
        $exclude = array_merge($exclude, array('escape'));
        $keys = array_diff(array_keys($options), $exclude);
        $values = array_intersect_key(array_values($options), $keys);
        $escape = $options['escape'];
        $tmp_attributes = array();
        foreach ($keys as $index => $key) {
            $tmp_attributes[str($index)->toLowerCase()->value] = $key;
        }
        $attributes = array();
        foreach ($tmp_attributes as $index => $key) {
            $attributes[] = $this->__formatAttribute($key, $values[$index], $escape);
        }
        return implode(' ', $attributes);
    }

    protected function __formatAttribute($key, $value, $escape = true)
    {
	    if (is_numeric($key)) {
	        return '';
	    }
        $minimizedAttributes = array('compact', 'checked', 'declare', 'readonly', 'disabled', 'selected', 'defer', 'ismap', 'nohref', 'noshade', 'nowrap', 'multiple', 'noresize');

        if (in_array($key, $minimizedAttributes) && (($value === 1) || ($value === true) || ($value === 'true') || ($value == $key))) {
            return $key.'="'.$key.'"';
        } else {
            return $key.'="'.($escape ? str($value)->xmlEntities(ENT_COMPAT) : $value).'"';
        }
    }

	function url($url = null, $full = false)
	{
	    $url = new str($url);
	    if (! $url->length) {
	        throw new ArgException();
	    }
		if ($url->contains('://') || $url->startsWith('javascript:') || $url->startsWith('mailto:') || $url->startsWith('#')) {
			return $url->toString();
		} elseif ($url->startsWith('/')) {
			return ($full ? Application::rootUrl() : Application::rootUrlPath()).($url->toString());
		} else {
	        throw new ArgException();
		}
	}
}

class CSSBackgroundImage
{
    protected $url;
    protected $left;
    protected $top;
    protected $width;
    protected $height;
}

class CSSBlock
{
    protected $url;
    protected $left;
    protected $top;
    protected $width;
    protected $height;
}

?>
